package com.tjbank.cssys.service.config;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ValidatorConfig {
    
    @Bean
    public Validator validator() throws FileNotFoundException , IOException {
        // 从service模块中暂时还无法读取该配置文件,先暂时放置到start模块中
        InputStream inputStream=null;
        try {
            inputStream = this.getClass().getResourceAsStream("/META-INF/validation/constraints-iam.xml");

            ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
                    .configure()
                    .addMapping(inputStream)
                    // 将fail_fast设置为true即可，如果想验证全部，则设置为false或者取消配置即可
                    .addProperty("hibernate.validator.fail_fast", "true")
                    .messageInterpolator(new ResourceBundleMessageInterpolator())
                    .buildValidatorFactory();
            return factory.getValidator();
        } catch (Exception e) {
            throw e;
        }finally {
            inputStream.close();
        }
    }
}